/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：音频播放器
* CreateTime：2020-05-20 11:33:48
* Version：1.0
* Modify Recorder：
*************************************************/

using TinyToolKit.Sound;
using UnityEngine;
using UnityEngine.UI;

namespace TinyToolKit
{
    public class AudioPlayer : MonoBehaviour
    {
        public Slider slider;

        private bool isPlaying;
        private float audioLength;
        private AudioSource _audioSource;
        [SerializeField]
        private AudioClip clip;
        private TSoundManager _soundManager;

        private void Start()
        {
            if (_soundManager == null)
                _soundManager = TinyTool.Instance.GetManager<TSoundManager>();
            
            if (slider == null)
                slider = gameObject.GetOrAddComponent<Slider>(); 
            
            slider.onValueChanged.AddListener((value) =>
            {
                if (_audioSource != null)
                    _audioSource.time = value * audioLength;
            });

            PlayAudio(clip);
        }
        
        private void Update()
        {
            if (isPlaying && slider != null && clip != null && _audioSource != null)
            {
                slider.value = _audioSource.time / clip.length;
            }
        }

        #region Public Func
        /// <summary>
        /// 播放音效
        /// </summary>
        public void PlayAudio(AudioClip clip)
        {
            this.clip = clip;
            _soundManager.PlayUISound(clip);
            audioLength = clip.length;
            AudioItem item = _soundManager.GetUISoundAudio(clip);
            _audioSource = item.AudioSource;
            isPlaying = true;
        }

        /// <summary>
        /// 暂停播放
        /// </summary>
        public void PauseAudio()
        {
            _soundManager.Pause(AudioItemType.UISound,clip);
            isPlaying = false; 
        }

        /// <summary>
        /// 继续播放
        /// </summary>
        public void ResumeAudio()
        {
            _soundManager.Resume(AudioItemType.UISound,clip); 
            isPlaying = true;
        }
        
        /// <summary>
        /// 获取当前播放的进度
        /// </summary>
        public string GetCurTimeProgress()  
        {
            string allTimeStr = TinyUtility.Time.ConvertSecondsToTime((int)clip.length);
            string curTimeStr = TinyUtility.Time.ConvertSecondsToTime((int)_audioSource.time);
            return curTimeStr + "/" + allTimeStr;
        }
        #endregion
    }
}
